<?php

namespace App\Http\Controllers\Api;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $per_page = $request->get('per_page',10);
        $current_page = $request->get('current_page',1);
        $withPage = $request->get('with_page',false);
        $withLevel = $request->get('with_level',false);
        $query = Category::query();
        if ($withLevel) {
            $data = $query->where('parent_id',null)->with('children')->get();
        }else{
            if ($withPage) {
                $data = $query->forPage($current_page)->paginate($per_page);
            } else {
                $data = $query->get();
            }
        }
        return $this->success($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $name = $request->get('name');
        $parent_id = $request->get('parent_id',NULL);
        $order = $request->get('order');
        $slug = $request->get('slug');
        $category = Category::query()->create(['name'=>$name,'parent_id'=>$parent_id,'order'=>$order,'slug'=>$slug]);
        return $category;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return Category::query()->find($id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $name = $request->get('name');
        $parent_id = $request->get('parent_id',NULL);
        $order = $request->get('order');
        $slug = $request->get('slug');
        $category = Category::query()->find($id)->update(['name'=>$name,'parent_id'=>$parent_id,'order'=>$order,'slug'=>$slug]);
        return $category;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
